package org.wzq.controller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.wzq.biz.Section;
import org.wzq.biz.User;
import org.wzq.dao.SectionDao;
import org.wzq.dao.UserDao;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * project: spring-mvc-forum
 * ate: 14-9-16
 * author: wzq
 * description: TODO
 */

@Controller
public class HomeController {
    protected final Log logger = LogFactory.getLog(getClass());

    @Autowired
    private UserDao userDao;

    @Autowired
    private SectionDao sectionDao;

    public void printReq(HttpServletRequest req) {
        logger.info(req.getMethod() + "  " + req.getRequestURI());
    }

    @RequestMapping(value = {"/", "home"}, method = RequestMethod.GET)
    public ModelAndView home(HttpServletRequest req, HttpServletResponse res) throws IOException {
        printReq(req);

        Map<String, Object> map = new HashMap<String, Object>();

        // 未登录
        User user = (User) req.getSession().getAttribute("user");
        if (user == null) {
            System.out.println("未登录");
            return new ModelAndView("home", "map", map);
        }

        System.out.println("已登录，user = " + user);
        map.put("userId", user.getUserId());
        map.put("userType", user.getUserType());
        return new ModelAndView("home", "map", map);
    }

    @RequestMapping(value = "signup", method = {RequestMethod.GET})
    public ModelAndView signup(HttpServletRequest req, HttpServletResponse res) throws IOException {
        printReq(req);
        return new ModelAndView("signup");
    }

    @ResponseBody
    @RequestMapping(value = "signup", method = {RequestMethod.POST})
    public String signup2(HttpServletRequest req, HttpServletResponse res) throws IOException {
        printReq(req);

        InputStream inputStream = req.getInputStream();
        String str = IOUtils.stream2String(inputStream, "utf-8");
        JSONObject json = new JSONObject(str);
        String name = json.getString("name");
        String pwd = json.getString("password");
        String sex = json.getString("sex");

        User user = userDao.getUserByName(name);
        JSONObject retJson = new JSONObject();
        if (user == null) {
            user = new User(name, sex, pwd);
            userDao.saveOrUpdate(user);
            req.getSession().setAttribute("user", user);
            retJson.put("isSucc", "true");
            return retJson.toString();
        } else {
            retJson.put("isSucc", "false");
            retJson.put("errMsg", "该用户名已经被注册");
            return retJson.toString();
        }
    }

    @RequestMapping(value = "signin", method = {RequestMethod.GET})
    public ModelAndView signin(HttpServletRequest req, HttpServletResponse res) throws IOException {
        printReq(req);
        return new ModelAndView("signin");
    }

    @ResponseBody
    @RequestMapping(value = "signin", method = {RequestMethod.POST})
    public String signin2(HttpServletRequest req, HttpServletResponse res) throws IOException {
        printReq(req);

        InputStream inputStream = req.getInputStream();
        String str = IOUtils.stream2String(inputStream, "utf-8");
        JSONObject json = new JSONObject(str);
        String name = json.getString("name");
        String pwd = json.getString("password");
        User user = userDao.isUserAndPwdMatch(name, pwd);

        JSONObject retJson = new JSONObject();
        if (user != null) {
            logger.info("登录成功");
            req.getSession().setAttribute("user", user);
            retJson.put("isSucc", "true");
            return retJson.toString();
        } else {
            logger.info("登录失败");
            retJson.put("isSucc", "false");
            retJson.put("errMsg", "用户名或密码错误");
            return retJson.toString();
        }
    }

    @RequestMapping(value = "signout", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView signout(HttpServletRequest req, HttpServletResponse res) throws IOException {
        printReq(req);
        HttpSession session = req.getSession();
        session.removeAttribute("user");
        session.invalidate();
        return new ModelAndView("home");
    }

    @RequestMapping(value = "profile", method = RequestMethod.GET)
    public ModelAndView profile(HttpServletRequest req, HttpServletResponse res) throws IOException {
        User user = (User) req.getSession().getAttribute("user");
        return new ModelAndView("profile", "user", user);
    }

    @RequestMapping(value = "sections", method = {RequestMethod.GET})
    public ModelAndView sections(HttpServletRequest req, HttpServletResponse res) throws IOException {
        printReq(req);
        List<Section> sectionList = sectionDao.getSectionAll();
        return new ModelAndView("sections", "sectionList", sectionList);
    }

//    @RequestMapping(value = "uploadFile", method = {RequestMethod.POST})
//    public ModelAndView uploadFile(HttpServletRequest req, HttpServletResponse res) throws IOException {
//        printReq(req);
//        String contentType = req.getHeader("Content-type");
//        System.out.println("contentType = " + contentType);
//        int indexStart = contentType.indexOf("boundary=");
//        int indexEnd = contentType.indexOf(";", indexStart);
//        if (indexEnd < 0) {
//            indexEnd = contentType.length();
//        }
//        String boundary = contentType.substring(indexStart,indexEnd);
//        System.out.println("boundary = " + boundary);
//
//        //----------------获取文件/表单 ------------------
//        // startwith '--${boundary}' endwith '--${boundary}--'
//        java.io.InputStream in = req.getInputStream();
//        String s = IOUtils.stream2String(in, "utf8");
//        System.out.println("s = " + s);
//
//        return new ModelAndView("zz");
//    }

    @RequestMapping(value = "uploadFile", method = {RequestMethod.POST})
    @ResponseBody
    public String uploadFile(@RequestParam("name") String name, @RequestParam("file") MultipartFile file)
            throws IOException {
        if (file.isEmpty()) {
            System.out.println("null file");
            return "null file";
        }

        // save the file
        byte[] bytes = file.getBytes();
        // Creating the directory to store file
        String rootPath = System.getProperty("catalina.home");
        File dir = new File(rootPath + File.separator + "tmpFiles");
        if (!dir.exists())
            dir.mkdirs();

        // Create the file on server
        File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
        stream.write(bytes);
        stream.close();

        logger.info("Server File Location=" + serverFile.getAbsolutePath());
        return "You successfully uploaded file=" + name;
    }

    @RequestMapping(value = "uploadMultipleFile", method = {RequestMethod.POST})
    @ResponseBody
    public String uploadMultiFile(@RequestParam("name") String[] names, @RequestParam("file") MultipartFile[] files)
            throws IOException {

        if (names.length != files.length) {
            return "Mandatory information missing";
        }


        String message = "";
        for (int i = 0; i < names.length; i++) {
            MultipartFile file = files[i];
            String name = names[i];
            try {
                byte[] bytes = file.getBytes();

                // Creating the directory to store file
                String rootPath = System.getProperty("catalina.home");
                File dir = new File(rootPath + File.separator + "tmpFiles");
                if (!dir.exists())
                    dir.mkdirs();

                // Create the file on server
                File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();

                logger.info("Server File Location=" + serverFile.getAbsolutePath());
                message = message + "You successfully uploaded file=" + name + "<br />";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        }
        return message;
    }
}
